package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;

import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    //1. 查询吐槽列表
    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    //2. 据id查询
    public Spit findById(String spitId) {
        return spitDao.findById(spitId).get();
    }

    //3. 添加数据
    public void add(Spit spit) {
        //3.1 自动升成id
        spit.set_id(idWorker.nextId() + "");
        spitDao.save(spit);
    }

    //4. 删除数据
    public void dele(String spitId) {
        spitDao.deleteById(spitId);
    }

    //5.修改吐槽
    public void update(Spit spit) {
        spitDao.save(spit);
    }

    //6.点赞         传统方式效率较低
    public void thumbup(String spitId) {
        Spit spit = spitDao.findById(spitId).get();
        spit.setThumbup(spit.getThumbup() + 1);
        spitDao.save(spit);

    }

    //6.点赞 2（使用mango模板完成）
    public void thumbup2(String spitId) {
        //6.1 定义查询条件
        Query quary = new Query();
        Criteria criteria = new Criteria("_id").is(spitId);
        quary.addCriteria(criteria);
        //6.2 定义要修改的对象
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.updateFirst(quary, update, "spit");
    }
    //7. 据parentid分页查询
    public PageResult findByParentid(String parentid, int page, int size) {
        Page<Spit> spitPage = spitDao.findByParentid(parentid,PageRequest.of(page-1,size));
        return new PageResult(spitPage.getTotalElements(),spitPage.getContent());
    }
 /*   //7.据parentId分页查询
    public PageResult findByParentId(String parentid, int page, int size) {
        Page<Spit> page1 = spitDao.findByParentId(parentid,PageRequest.of(page-1,size));
        return new PageResult(page1.getTotalElements(),page1.getContent());
    }*/
}
